package com.trsj.lnsj.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.trsj.lnsj.common.DataResponse;
import com.trsj.lnsj.common.MsgStatus;
import com.trsj.lnsj.entity.UserDTO;
import com.trsj.lnsj.model.PayLog;
import com.trsj.lnsj.service.IUserService;
import com.trsj.lnsj.service.WechatPayService;
import com.trsj.lnsj.util.QiNiu;
import com.trsj.lnsj.util.ResponseHelper;
import com.trsj.lnsj.util.UploadHelper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
@Api(value="",tags="")
@RestController
@RequestMapping(value = "/api/user/*")
@CrossOrigin
public class UserController {
    private Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private IUserService userBiz;
    @Autowired
    private Environment env;
    @Autowired
    private WechatPayService wechatService;

    /**
     * 保存用户个人信息
     * 
     * @param user
     * @param session
     * @return
     */
    @ApiOperation(value = "保存用户个人信息", notes = "保存用户个人信息")
    @RequestMapping(value = "/saveUserInfo", method = RequestMethod.POST)
    public DataResponse saveUserInfo(UserDTO user, HttpSession session) {
        // 查询是否存在该用户
        DataResponse resp = userBiz.saveUserInfo(user);
        return resp;
    }

    /**
     * 用户登录接口
     * 
     * @param user
     * @param session
     * @return
     */
    @ApiOperation(value = "用户登录接口", notes = "用户登录接口")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public DataResponse loginByShortMsg(UserDTO user, HttpSession session, HttpServletRequest request) {
        logger.info("requestHeader={}", request.getHeaderNames());
        // 查询是否存在该用户
        DataResponse resp = userBiz.login(user);
        return resp;
    }

    /**
     * 保存用户个人信息
     * 
     * @param user
     * @param session
     * @return
     */
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public DataResponse hello(String name, HttpSession session) {
        // 查询是否存在该用户
        DataResponse resp = ResponseHelper.getSuccessResponse("name", name);
        return resp;
    }

    /**
     * 向用户手机发送登录短信验证码
     * 
     * @param mobilephone
     * @param type(0:登录,1:注册)
     * @return
     * @throws org.json.JSONException
     */
    @RequestMapping(value = "/sendMsgCode", method = RequestMethod.GET)
    public DataResponse sendMsgCode(String mobilephone, String type, HttpSession session) {
        DataResponse resp = userBiz.sendMsgCode(mobilephone, type, session);
        return resp;
    }

    /**
     * 用户参加有偿活动支付接口
     * 
     * @param payAmount支付金额
     * @param orderNo订单号
     * @return
     */
    @ApiOperation(value = "用户参加有偿活动支付接口", notes = "用户参加有偿活动支付接口")
    @RequestMapping(value = "/alipay", method = RequestMethod.POST)
    public DataResponse alipay(float payAmount, String orderNo, HttpServletRequest request) {
        DataResponse res = userBiz.alipay(payAmount, orderNo, request);
        return res;
    }

    /**
     * 通过快乐号判断是否存在该用户
     * 
     * @param mobilephone
     * @return
     */
    @ApiOperation(value = "通过快乐号判断是否存在该用户", notes = "通过快乐号判断是否存在该用户")
    @RequestMapping(value = "/selectUserByHappyNo", method = RequestMethod.GET)
    public DataResponse selectUserByHappyNo(String happyNo, HttpServletRequest request) {
        DataResponse res = null;
        res = userBiz.selectUserByHappyNo(happyNo);
        return res;
    }

    /**
     * 通过手机号判断是否存在该用户
     * 
     * @param mobilephone
     * @return
     */
    @ApiOperation(value = "通过手机号判断是否存在该用户", notes = "过手机号判断是否存在该用户")
    @RequestMapping(value = "/selectUserByMobilephone", method = RequestMethod.GET)
    public DataResponse selectUserByMobilephone(String mobilephone) {
        DataResponse res = userBiz.selectUserByMobilephone(mobilephone);
        return res;
    }

    @ApiOperation(value = "Alipay Notify回调", notes = "Alipay Notify回调")
    @ApiImplicitParams({})
    @PostMapping("/appAlipayNotify")
    public DataResponse appAliPayNotify(HttpServletRequest request) {
        DataResponse res = userBiz.appAliPayNotify(request);
        return res;
    }

    @PostMapping("/wechatPayOrder")
    public DataResponse wechatPayOrder(PayLog payLog, HttpServletRequest request) {
        DataResponse res = wechatService.orderAppPay(payLog, request);
        return res;
    }

    @ApiOperation(value = "Wechat Notify回调", notes = "Wechat Notify回调")
    @ApiImplicitParams({})
    @PostMapping("/wechatOrderNotify")
    public DataResponse wechatOrderNotify(HttpServletRequest request) {
        DataResponse res = wechatService.wechatOrderNotify(request);
        return res;
    }

    @ApiOperation(value = "上传头像", notes = "上传文件 文件参数名为file")
    @RequestMapping(value = "/uploadHeadPic", method = RequestMethod.POST)
    public DataResponse upload(HttpServletRequest request,@RequestParam(name="userId" ,required=true)Long userId) {
         UserDTO user=userBiz.selectByUserId(userId);
         if(user==null)
             return new DataResponse(MsgStatus.PARAMS_INVALID,"用户ID不存在");
             
        List<MultipartFile> file = ((MultipartHttpServletRequest) request).getFiles("file");
         String url= setSingleImage(file);
         if(StringUtils.isEmpty(url)) {
            
        return new DataResponse(MsgStatus.STATUS_FAILED);
                 }
         user.setHeadPic(url);
         userBiz.save(user);
        return new DataResponse(MsgStatus.STATUS_OK, url);
    }
    
    public String setSingleImage( List<MultipartFile> imgFiles) {
        //imgFile.getInputStream();
        StringBuilder imgSb = new StringBuilder();
        InputStream in = null;
        if (imgFiles!=null) {
            for (MultipartFile imgFile:imgFiles) {
                if (imgFile != null && StringUtils.isNotBlank(imgFile.getName())) {
                    String fileName = String.valueOf(System.currentTimeMillis()) + imgFile.getOriginalFilename();
                    String tmpPath = env.getProperty("zlnsj.temp.file.path");
                    String path = tmpPath;
                    File fileDir = new File(path);
                    if (!fileDir.exists()) {
                        fileDir.mkdir();
                    } else if (fileDir.isDirectory()) {
                        File imgFileTemp = new File(path + File.separator + fileName);
                        if (!imgFileTemp.exists()) {
                            try {
                                imgFileTemp.createNewFile();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                   logger.error("上传 imgFileTemp 错误 ",e);
                                e.printStackTrace();
                            return "";
                            }
                        }
                        try {
                            in = imgFile.getInputStream();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            try {
                                in.close();
                            } catch (IOException e2) {
                                // TODO Auto-generated catch block
                                e2.printStackTrace();
                                logger.error("imgFile.getInputStream() error ",e);
                                
                            }
                            return "";
                        }
                        UploadHelper.writeToNewFile(in, imgFileTemp.getAbsolutePath());
                        try {
                            in.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        QiNiu.uploadFile(imgFileTemp, imgFileTemp.getName(), QiNiu.bucket, 2);
                        if (StringUtils.isEmpty(imgSb.toString())) {
                            imgSb.append(env.getProperty("zlnsj.activity.image.path") + "/" + imgFileTemp.getName());
                        } else {
                            imgSb.append(";" + env.getProperty("zlnsj.activity.image.path") + "/" + imgFileTemp.getName());
                        }
                    }
                    fileDir.delete();
                    
                }
            }
        }
        return imgSb.toString();
    }

    /**
     * 用户更新密码
     * @param mobilephone
     * @param oldPwd
     * @param newPwd
     */
    @RequestMapping(value = "/updatepwd", method = RequestMethod.POST)
    public DataResponse updateUserPwd(String mobilephone, String oldPwd, String newPwd) {
        DataResponse res = userBiz.updateUserPwd(mobilephone,oldPwd,newPwd);
        return res;
    }

    /**
     * 添加用户参加活动信息
     * @param happyNo
     * @param actid
     * @return
     */
//    @RequestMapping(value = "/saveUserActivity", method = RequestMethod.POST)
//    public DataResponse saveUserActivity(String happyNo, int actid) {
//        DataResponse resp = userBiz.saveUserActivity(happyNo,actid);
//        return resp;
//    }

    /**
     * 修改用户昵称接口
     * @param happyNo
     * @param actid
     * @return
     */
    @RequestMapping(value = "/updateUserNickName", method = RequestMethod.POST)
    public DataResponse updateUserNickName(long userId, String nickname) {
        DataResponse resp = userBiz.updateUserNickName(userId,nickname);
        return resp;
    }

    /**
     * 修改用户签名接口
     * @param happyNo
     * @param actid
     * @return
     */
    @RequestMapping(value = "/updateUserSignature", method = RequestMethod.POST)
    public DataResponse updateUserSignature(long userId, String signature) {
        DataResponse resp = userBiz.updateUserSignature(userId,signature);
        return resp;
    }

    /**
     * 好友信息
     * @param happyNo
     * @param actid
     * @return
     */
    @RequestMapping(value = "/queryUserFriendsInfo", method = RequestMethod.POST)
    public DataResponse queryUserFriendList(String happyNo) {
        DataResponse resp = userBiz.queryUserFriendsInfo(happyNo);
        return resp;
    }

}
